#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*-  
 

__author__ = "Nick Milon"

 
import models
db =models.db
users = models.ApplUser
ApplService = models.ApplService
ApplUser=models.ApplUser
from google.appengine.ext import webapp

from google.appengine.ext.webapp.util import run_wsgi_app
 
from google.appengine.api.labs import taskqueue
from django.utils import simplejson as json 
from google.appengine.api import urlfetch 
import logging
import hashlib
import time 
#import tropo_web_api
from tropo_web_api import Tropo 
#from .import tropo_web_api
TropoApplTokenMessage="e79a821159b1594f8d6de2807fca8e965f313d99d070b908e441ebf6d8218fc333312b22769a0d418068d3c2" 
TropoApplTokenVoice="498ef1e6fc61fb42b1a2cf790f6f6103628e1cb9749d66b124043559552e6933739dbd73efd47ee9ca11d27b"

def MessageSMS(MsgText, PhoneNumber, next=""):
    tropo = Tropo()
    tropo.message(MsgText, PhoneNumber, channel='TEXT', network='SMS', timeout=5, name="FOOXXXXXXXXXXXXXXXXX")
    if next !="":tropo.on(event="continue",next=next)
    #logging.info("tropoRepr:"+repr(tropo))
    json = tropo.RenderJson() 
    #logging.info ("MessageSMS Json: %s " % json)
    return json
def TropoHungUp(): 
    tropo=Tropo()
    tropo.hangup()
    json=tropo.RenderJson() 
    return json 

def tropoFetch(token, smsUID):
    _baseUri="http://api.tropo.com/1.0/sessions" 
    uriTropo="%s?token=%s&action=create&smsUID=%s" %(_baseUri, token, smsUID)
    rpc = urlfetch.create_rpc(deadline=10)
    logging.info("Fetching url:"+ uriTropo)
    urlfetch.make_fetch_call(rpc, uriTropo, payload=None, method="GET", headers={}, allow_truncated=False, follow_redirects=False) 
    try:
        result = rpc.get_result()
         
        if result.status_code == 200:
            logging.info ("tropoFetch succes"+str(result.status_code))
            logging.info ('tropoFetch content'+str(result.content) )
    except:# urlfetch.DownloadError:
        logging.error ("tropoFetch failed:"+str(result.status_code))     
 

class RQHsms(webapp.RequestHandler): 
    def prepareResponce(self):
        self.response.headers['mimetype'] ="application/json"
        #self.response.headers['Content-Type'] ="application/jsonrequest"
    def get(self, arg): 
        self.prepareResponce()
        logging.info('sms request'+arg) 
        callback=self.request.get('callback', "") 
        if arg=="smsReq":
            msgToNum=self.request.get('msgToNum', None)
            if msgToNum.startswith(' '):msgToNum="+" + msgToNum[1:]  #temporary  must use ? http://docs.python.org/library/base64.html?#module-base64 
            msgTxt=self.request.get('msgTxt', None) 
            #msgTxt=msgTxt.encode('utf-8') 
            smsUID="%s%s" %(msgToNum, repr(time.time()))
            smsUID=hashlib.sha224(smsUID).hexdigest()  
            logStr="smsUID:%s,msgToNum:%s,msgTxt:%s" %(smsUID, msgToNum, msgTxt)
            logging.info(logStr)
            taskqueue.add(url='/smsTQ/', params={'smsUID':smsUID,'msgToNum': msgToNum,'msgTxt':msgTxt})
            logging.info('TQ-Added')
            resp={'smsUID':smsUID, 'result':200}  
            if callback !='':resp = '%s(%s)' % (callback, resp)
            
            #self.response.headers['mimetype'] ="application/json" 
            self.response.out.write(repr(resp))
        if arg=="smsStatus":
            smsUID=self.request.get('msgUID', None)
            if smsUID is None: resp= {'result':500}   
            else: 
                resp= {'result':200}
            if callback !='':resp = '%s(%s)' % (callback, resp)
            self.response.out.write(repr(resp))
                
    def post(self,  action):
        self.prepareResponce()
        jsonToTropo="{}"
        if action == "msg.json":                        #TODO temporary should  return http 500 something 
            jsonFromTropo=json.loads(self.request.body)
            logging.info('jsonFromTropo:'+ str(jsonFromTropo))
            tropoSession=jsonFromTropo['session']
            smsUID=tropoSession['parameters']['smsUID']
            smsEntity= models.msgSMS.get_by_key_name(smsUID, rpc= db.create_rpc(read_policy=db.EVENTUAL_CONSISTENCY)) 
            if smsEntity is None:
                logging.error('RQHsms cant get entity')
            else:
                UrlResult=self.request.path_info.replace(action, "msgresults.json")
                UrlResult=self.request.host_url+UrlResult
                Txt=smsEntity.msgTxt
                Txt=Txt.encode('utf-8')
                jsonToTropo=MessageSMS(Txt, smsEntity.msgToNum, UrlResult) 
                smsEntity.status=1
                smsEntity.put
                logging.info('Num='+smsEntity.msgToNum)
                logging.info(Txt)
                
        elif action == "msgresults.json":  
            jsonFromTropo=json.loads(self.request.body)
            #sessionId=jsonFromTropo['result']['sessionId']
             
            logging.info(repr(jsonFromTropo))    
            jsonToTropo= TropoHungUp()  
        #self.response.headers['mimetype'] ="application/json" 
        self.response.out.write(jsonToTropo)        
        
class RQHsmsTQ(webapp.RequestHandler): 
    def post(self):
        #logging.info("request:"+str(self.request))
        msgToNum=self.request.get('msgToNum', None)
        msgTxt=self.request.get('msgTxt', None)
        smsUID=self.request.get('smsUID', None) 
        logStr="smsUID:%s,msgToNum:%s,msgTxt:%s" %(smsUID, msgToNum, msgTxt)
        logging.info(logStr) 
        smsEntity= models.msgSMS(key_name=smsUID, msgToNum=msgToNum, msgTxt=msgTxt, status=1) 
        smsEntity.put() 
        tropoFetch(TropoApplTokenMessage, smsUID) 
        

application = webapp.WSGIApplication(
                                     [ 
                                    (r"/sms/(.*)", RQHsms),
                                    (r"/smsTQ/.*", RQHsmsTQ),    
                                    ('/', RQHsms)],
                                     debug=True)

def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
